﻿using AutoMapper;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ross.Service
{
    public class UsersService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Users, int> repository;

        public UsersService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Users, int>(dbContext);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="vm"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public ResultDto<Service.Dto.oUser> Login(Dto.LoginVM vm, string token)
        {
            ResultDto<Service.Dto.oUser> result = new ResultDto<Service.Dto.oUser>();
            var obj = repository.GetAllList(o => o.UserName == vm.username || o.EmpID==vm.username).FirstOrDefault();
            if (obj != null)
            {
                if (obj.password != vm.password)
                {
                    result.message = "invaild password";
                    result.status = 500;
                }
                else
                {
                    result.status = 200;
                    result.datas = Mapper.Map<Service.Dto.oUser>(obj);
                    result.token = token;
                }
            }
            else
            {
                result.message = "invaild username";
                result.status = 500;
            }
            return result;
        }
        /// <summary>
        /// 检查用户有效性
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool ValidateUser(string username, string password)
        {
            var obj = repository.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
            if (obj != null)
            {
                if (obj.password != password)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取单页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultDto<Dto.oUser> GetByID(int id)
        {
            ResultDto<Dto.oUser> result = new ResultDto<Dto.oUser>();
            var obj = repository.Get(id);
            if (obj != null)
            {
                result.status = 200;
                result.datas = Mapper.Map<Dto.oUser>(obj);
            }
            else
            {
                result.message = "user is not exist";
                result.status = 500;
            }
            return result;
        }

        //添加
        public ResultDto<bool> Create(Users users)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var user = repository.GetAllList(o => o.UserName == users.UserName || o.EmpID == users.EmpID).Count;
            if (user > 0)
            {
                result.message = "user is exist";
                result.status = 500;
                result.datas = false;
            }
            else
            {
                try
                {
                    //var model = Mapper.Map<Users>(users);
                    var obj = repository.Insert(users);
                    result.status = 200;
                    result.datas = true;
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.datas = false;
                }
            }
            return result;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultDto<bool> Delete(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                repository.Delete(id);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ResultDto<bool> Update(Dto.oUser user)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.GetAllList(o => (o.EmpID == user.EmpID || o.UserName == user.UserName) && o.ID != user.ID).FirstOrDefault();
                if (obj == null)
                {
                    var model = repository.Get(user.ID);
                    model.EmpID = user.EmpID;
                    model.EmpName = user.EmpName;
                    model.Department = user.Department;
                    model.IsActive = user.IsActive;
                    model.AuthorizedDepartment = user.AuthorizedDepartment;
                    repository.Update(model);
                    result.status = 200;
                    result.datas = true;
                }
                else
                {
                    result.message = "The user is exist";
                    result.status = 500;
                    result.datas = false;
                }
            }
            catch (Exception ex)
            {
                result.status = 500;
                result.message = Common.GetInnerException(ex);
            }
            return result;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<Dto.oUser>> GetAllList()
        {
            ResultDto<List<Dto.oUser>> result = new ResultDto<List<Dto.oUser>>();
            var lists = repository.GetAllList();
            result.datas = Mapper.Map<List<Dto.oUser>>(lists);
            return result;
        }

        public ResultDto<List<Dto.oUser>> GetPageList(int pageindex = 1, int pagesize = 10, string username = "", string empid = "", string department = "")
        {
            ResultDto<List<Dto.oUser>> result = new ResultDto<List<Dto.oUser>>();
            Expression<Func<Users, bool>> expression = o => o.ID > 0;
            if (!string.IsNullOrEmpty(username))
                expression = expression.ExpressionAnd(t => t.UserName.Contains(username));
            if (!string.IsNullOrEmpty(empid))
                expression = expression.ExpressionAnd(t => t.EmpID == empid);
            if (!string.IsNullOrEmpty(department))
                expression = expression.ExpressionAnd(t => t.Department.Contains(department));
            var resp = repository.GetPageList(pageindex, pagesize, expression);
            result = Mapper.Map<ResultDto<List<Dto.oUser>>>(resp);
            return result;
        }
        /// <summary>
        /// 密码修改
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ResultDto<bool> UpdatePsw(Dto.UptPsw vm)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var obj = repository.Get(vm.UserId);
            if (obj == null)
            {
                result.message = "user is not exist";
                result.status = 500;
                result.datas = false;
            }
            else
            {
                try
                {
                    if (vm.OrgPassword != obj.password)
                    {
                        result.datas = false;
                        result.status = 500;
                        result.message = "The original password is wrong";
                    }
                    else
                    {
                        obj.password = vm.Password;
                        repository.Update(obj);
                        result.datas = true;
                    }
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.datas = false;
                    result.status = 500;
                }
            }
            return result;
        }
        /// <summary>
        /// 重设用户密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public ResultDto<bool> ResetPsw(int userId, string password)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var obj = repository.Get(userId);
            if (obj == null)
            {
                result.message = "user is not exist";
                result.status = 500;
                result.datas = false;
            }
            else
            {
                try
                {
                    obj.password = password;
                    repository.Update(obj);
                    result.datas = true;
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.datas = false;
                    result.status = 500;
                }
            }
            return result;
        }

        public void Dispose()
        {
            dbContext.Dispose();
        }
    }

}
